﻿using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Dto.DictionaryData;
using SHZY.BaseData.Interfaces.Common;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Helper;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Dto.DictionaryData;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：客户分类.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "CustomerClassify", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBaseCustomerClassifyService : IComBaseCustomerClassifyService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<DictionaryDataEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBaseCustomerClassifyService"/>客户类型的新实例.
    /// </summary>
    public ComBaseCustomerClassifyService(
        ISqlSugarRepository<DictionaryDataEntity> baseDictionarydataRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager,
        IFileManager fileManager)
    {
        _repository = baseDictionarydataRepository;
        _dataInterfaceService = dataInterfaceService;
        _db = context.AsTenant();
        _userManager = userManager;
        _fileManager = fileManager;
    }

    /// <summary>
    /// 获取客户类型.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<BaseDictionarydataInfoOutput>();
    }

    /// <summary>
    /// 获取客户类型列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] BaseDictionarydataListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<DictionaryDataEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.fullName), it => it.FullName.Contains(input.fullName))
            .WhereIF(!string.IsNullOrEmpty(input.enCode), it => it.EnCode.Contains(input.enCode))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.FullName.Contains(input.keyword) || it.EnCode.Contains(input.keyword))
            .Where(it => it.DictionaryTypeId == "450896517276895493")
            .Where(it => it.DeleteMark == null)
            .Select(it => new BaseDictionarydataListOutput
            {
                id = it.Id,
                fullName = it.FullName,
                enCode = it.EnCode,
                sortCode = (long)it.SortCode,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it=>it.id);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<BaseDictionarydataListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建客户类型.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] BaseDictionarydataCrInput input)
    {
        if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DictionaryTypeId == "450896517276895493" && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<DictionaryDataEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity)
            .IgnoreColumns(ignoreNullColumn: true)
            .CallEntityMethod(m => m.Creator())
            .ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取客户类型无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] BaseDictionarydataListQueryInput input)
    {
        return await _repository.Context.Queryable<DictionaryDataEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.fullName), it => it.FullName.Contains(input.fullName))
            .WhereIF(!string.IsNullOrEmpty(input.enCode), it => it.EnCode.Contains(input.enCode))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.FullName.Contains(input.keyword) || it.EnCode.Contains(input.keyword))
            .Where(it => it.DictionaryTypeId == "450896517276895493")
            .Where(it => it.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new BaseDictionarydataListOutput
            {
                id = it.Id,
                fullName = it.FullName,
                enCode = it.EnCode,
                sortCode = (long)it.SortCode,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
    }

    /// <summary>
    /// 导出客户类型.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] BaseDictionarydataListQueryInput input)
    {
        var exportData = new List<BaseDictionarydataListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<BaseDictionarydataListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"客户类型名称\",\"field\":\"fullName\"},{\"value\":\"客户类型编码\",\"field\":\"enCode\"},{\"value\":\"状态\",\"field\":\"enabledMark\"},{\"value\":\"排序\",\"field\":\"sortCode\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "客户类型.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<BaseDictionarydataListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除客户类型.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<DictionaryDataEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除​缺陷类别
                var isOk = await _repository.Context
                .Updateable<DictionaryDataEntity>()
                .SetColumns(it => new DictionaryDataEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id))
                .ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新客户类型.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] DictionaryDataUpInput input)
    {
        if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DeleteMark == null && x.Id != input.id && x.DictionaryTypeId == "450896517276895493"))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<DictionaryDataEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.FullName,
            it.EnCode,
            it.Description,
            it.SortCode,
            it.EnabledMark,
            it.DictionaryTypeId,
            it.LastModifyTime,
            it.LastModifyUserId,
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除客户类型.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<DictionaryDataEntity>()
                .SetColumns(it => new DictionaryDataEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(x => x.Id == id)
                .ExecuteCommandHasChangeAsync();

        if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };
        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] BaseDictionarydataInput input)
    {
        var output = new BaseDictionarydataImportDataOutput();
        foreach (var item in input.list)
        {
            try
            {
                if (await _repository.AnyAsync(x => x.EnCode == item.enCode && x.DeleteMark == null && x.DictionaryTypeId == "450896517276895493"))
                    throw Oops.Oh(ErrorCode.COM1004);

                if (!string.IsNullOrEmpty(item.sortCode))
                {
                    System.Text.RegularExpressions.Regex regex = new
                    System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
                    if (!regex.IsMatch(item.sortCode.ToString()))
                    {
                        item.exceptionMsg = "排序应该为整数！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                }

                var entity = item.Adapt<DictionaryDataEntity>();

                //验证参数信息
                if (string.IsNullOrEmpty(entity.FullName))
                {
                    item.exceptionMsg = "请输入客户类型名称！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (string.IsNullOrEmpty(entity.EnCode))
                {
                    item.exceptionMsg = "请输入客户类型编码！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (!string.IsNullOrEmpty(entity.Description))
                {
                    if (entity.Description.Trim().Length > 500)
                    {
                        item.exceptionMsg = "说明长度不能超过500字！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                }

                entity.DictionaryTypeId = "450896517276895493";
                entity.ParentId = "0";
                var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOK < 1)
                {
                    output.failResult.Add(item);
                    output.fnum++;
                }
                else
                {
                    output.snum++;
                }
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
        }
        else
        {
            output.resultType = 0;
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "客户类型模板.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "DicData_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!await _fileManager.ExistsFile(addFilePath))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D1801);
        }
    }

    #region PrivateMethod

    private string GetFileEncode(string filed)
    {
        switch (filed)
        {
            case "名称":
                return "fullName";

            case "编码":
                return "enCode";

            case "排序":
                return "sortCode";

            case "描述":
                return "description";

            default:
                return string.Empty;
        }
    }

    #endregion PrivateMethod
}